package com.syn.michat.im;

import com.syn.michat.im.service.PackageService;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

// ws://localhost:8086/michat/websocket
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer  {

    private static PackageService packageService;

    @Resource
    public void setSystemLogInfoService(PackageService packageService){
        WebSocketServer.packageService = packageService;
    };

    @OnOpen
    public void onOpen(Session session) {
    }

    /**
     * 接收到客户端消息时触发的方法
     */
    @OnMessage
    public void onMessage(String params,Session session) throws IOException {
        try {
            packageService.resPackageHandler(params, session);
        } catch (Exception e) {
            session.getBasicRemote().sendText("json转换出错");
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session){
        WebSocketSessionManager.remove(session);
        System.out.println(session.getId().toString());
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("onError" + error);
    }
}
